
<!doctype html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <title>模拟ajax的 script请求</title>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<button id="test">模拟jQuery.ajax的script请求</button>

<script type="text/javascript">
 
    /**
     * 模拟ajax的 script请求
     * @param  {[type]} options [description]
     * @return {[type]}         [description]
     */
    function createAjax(options) {

        if (typeof url === "object") {
            options = url;
            url = undefined;
        }

        options = options || {};

        /**
         * 参数
         * jQuery.ajaxSetup 是默认参数
         * @type {[type]}
         */
        var s = jQuery.ajaxSetup({}, options);

        // Deferreds
        // 异步机制
        var deferred = jQuery.Deferred();
        var completeDeferred = jQuery.Callbacks("once memory");

        /**
         * 实际返回的ajax对象
         * @type {Object}
         */
        var jqXHR = {}

        // 把jqXHR对象转化promise对象，幷加入complete、success、error方法
        deferred.promise(jqXHR).complete = completeDeferred.add;
        //别名
        jqXHR.success = jqXHR.done;
        jqXHR.error = jqXHR.fail;

        // 增加回调队列
        // complete: function() {
        //     console.log('局部事件complete')
        // },
        // error: function() {
        //     console.log('局部事件error请求失败时调用此函数')
        // },
        // success: function() {
        //     console.log('局部事件success')
        // }
        for (i in {
            success: 1,
            error: 1,
            complete: 1
        }) {
            jqXHR[i](s[i]);
        }

        function send(_, complete) {
            var script = jQuery("<script>").prop({
                async: true,
                charset: s.scriptCharset,
                src: s.url
            }).on(
                "load error",
                callback = function(evt) {
                    script.remove();
                    callback = null;
                    if (evt) {
                        complete(evt.type === "error" ? 404 : 200, evt.type);
                    }
                }
            );
            document.head.appendChild(script[0]);
        }


        function done(status, nativeStatusText, responses, headers) {
            var isSuccess = status >= 200 && status < 300 || status === 304;
            var success = jqXHR.success;
            var error = jqXHR.error;
            if (isSuccess) {
                deferred.resolveWith(document, [success, jqXHR]);
            } else {
                deferred.rejectWith(document, [jqXHR, error]);
            }
        }

        //发送请求
        send({
            Accept: "text/javascript, application/javascript, application/ecmascri"
        }, done);

        return jqXHR;
    }

    function show(data){
        $('body').append('<li>'+ data +'</li>');
    }

    $("#test").click(function(){
        //执行一个异步的HTTP（Ajax）的请求。
        var ajax = createAjax({
            url: 'http://code.jquery.com/jquery-latest.js',
            dataType: 'script',
            //请求完成后回调函数 (请求success 和 error之后均调用)
            complete: function() {
                show('局部事件complete')
            },
            error: function() {
                show('局部事件error请求失败时调用此函数')
            },
            success: function() {
                show('局部事件success')
            }
        })

        ajax.done(function() {
           show('deferred done')
        }).fail(function() {
            show('deferred fail')
        }).always(function() {
            show('deferred lways')
        })

    })


</script>
</body>
</html>